//
//  SCTextView.swift
//  weibo
//
//  Created by 阿城 on 15/12/14.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

class SCTextView: UITextView {

    var placeholder: String?{
        didSet{
            placeholderLabel.text = placeholder
//            placeholderLabel.sizeToFit()
        }
    }
    override var font: UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        addSubview(placeholderLabel)
        
        //监听手动输入
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        placeholderLabel.frame.size.width = frame.size.width - 10
//        placeholderLabel.backgroundColor = UIColor.redColor()
        placeholderLabel.sizeToFit()
    }
    
    @objc private func textChange(){
//        printLog(text.characters.count)
        placeholderLabel.hidden = text.characters.count != 0
    }
    
    private lazy var placeholderLabel:UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.grayColor()
        lab.text = "请输入文字~~~"
        lab.numberOfLines = 0
        lab.font = UIFont.systemFontOfSize(14)
        return lab
    }()
    
    private lazy var customInput: SCEmoticonKeyboard = {
        let view = SCEmoticonKeyboard()
        view.frame.size = CGSize(width: 10, height: 200)
//        view.backgroundColor = UIColor.redColor()
        return view
    }()
    
    var prepare: Bool = true
    
    deinit{
        //移除监听
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}

// MARK: - 对外接口
extension SCTextView{
    
    func EmoticonKeyboard(){
        //避免弹跳
        prepare = false
        resignFirstResponder()
        
        inputView = inputView == nil ? customInput : nil
        
        prepare = true
        becomeFirstResponder()
    }
    
    
    func setAtrributeStringWithEmoticon(emoticon: SCEmoticonModel){
        
        if emoticon.path != nil{
            
            let attribute = NSMutableAttributedString(attributedString: attributedText)
            
            let append = SCAttachment().getEmoticonAttributedString(emoticon, font: font!)
            
            let range = selectedRange
            
            attribute.replaceCharactersInRange(selectedRange, withAttributedString: append)
            
            attribute.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: attribute.length))
            attributedText = attribute
            
            //设置光标
            selectedRange.location = range.location + 1
            
        }else{
            insertText((emoticon.code! as NSString).emoji())
        }
    }
    
    var oringinalStr: String{
        var str = String()
        
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: []) { (info, range, _) -> Void in
            
//            printLog(info)
            
            if let attach = info["NSAttachment"] as? SCAttachment{
                str += attach.emoticonMod!.chs!
            }else{
                str += (self.attributedText.string as NSString).substringWithRange(range)
            }
            
        }
        return str
    }
    
}

class SCAttachment: NSTextAttachment {
    
    var emoticonMod: SCEmoticonModel?
    
    func getEmoticonAttributedString(emoticon: SCEmoticonModel, font: UIFont)->NSAttributedString{
        image = UIImage(named: emoticon.path!)
        bounds = CGRect(x: 0, y: -3, width: font.lineHeight, height: font.lineHeight)
        emoticonMod = emoticon
        return NSAttributedString(attachment: self)
    }
    
}


